
<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        :permission="permissionList"
        v-bind="bindVal"
        v-on="onEvent"
        :page.sync="page"
      >
        <template slot="menuLeft">
          <el-button type="primary" size="small" @click="myAdd">新增</el-button>
          <el-button type="primary" size="small" @click="delBatch">删除</el-button>
          <el-button type="primary" size="small" v-if="false" @click="handleExport">导出</el-button>
          <el-button type="primary" size="mini" @click="submitData">加入报表差错</el-button>
	   <div style="padding-left: 30px;display:inline-block;">
            <span style="color: red;font-size: 12px">注意：需与同一周期提交TVM编号保持一致</span>	   
          </div>
        </template>
        <template slot-scope="scope" slot="menu">
          <el-button
            icon="el-icon-check"
            :size="scope.size"
            :type="scope.type"
            v-if="scope.row.approvalStatus=='0'"
            @click="myEdit(scope.row)"
          >编辑</el-button>
          <el-button
            icon="el-icon-check"
            :size="scope.size"
            :type="scope.type"
            @click="myView(scope.row)"
          >预览</el-button>
          <el-button
            icon="el-icon-check"
            :size="scope.size"
            :type="scope.type"
            @click="openPastRecords(scope.row)"
            >查看历史记录</el-button
          >
        </template>
      </avue-crud>
      <el-dialog
        title="收款人确认"
        :visible="dialogFormVisible"
        append-to-body
        center
        :destroy-on-close="true"
      >
        <el-form>
          <el-form-item label="收款人账号">
            <el-input v-model="form1.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="收款人密码">
            <el-input v-model="form1.password" type="password" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmUser">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog
        :visible.sync="addVisableDialog"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :fullscreen="addchangeDialogFlag"
        :destroy-on-close="true"
        width="60%"
      >
        <div slot="title">
          <div>
            <span class="el-dialog__title">添 加</span>
            <div class="avue-crud__dialog__menu">
              <button
                class="el-dialog__headerbtn"
                style="margin-right:20px"
                @click.stop="addchangeDialog"
              >
                <i class="el-dialog__close el-icon-full-screen"></i>
              </button>
            </div>
            <button type="button" aria-label="Close" class="el-dialog__headerbtn">
              <i class="el-dialog__close el-icon el-icon-close"></i>
            </button>
          </div>
        </div>
        <el-form :model="formAdd">
          <dynamic-crud :data="tableDataAdd" :option="tableOptionAdd" title="手工清出明细" :rowAdd="rowAdd"></dynamic-crud>
          <avue-form
            v-model="formAdd.swStHandworkCleanRecord"
            :option="formOptionAdd"
            style="margin-top:38px"
          ></avue-form>
          <div class="bottom-menu">
            <el-button type="primary" @click="confirmObj">收款人确认</el-button>
            <el-button type="primary" @click="save">保存</el-button>
            <el-button type="primary" @click="addVisableDialog=false">取消</el-button>
          </div>
        </el-form>
      </el-dialog>

      <el-dialog
        :visible.sync="editVisableDialog"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :fullscreen="editchangeDialogFlag"
        width="60%"
      >
        <div slot="title">
          <div>
            <span class="el-dialog__title">编 辑</span>
            <div class="avue-crud__dialog__menu">
              <button
                class="el-dialog__headerbtn"
                style="margin-right:20px"
                @click="editchangeDialog"
              >
                 <i class="el-dialog__close el-icon-full-screen"></i>
              </button>
            </div>
            <button type="button" aria-label="Close" class="el-dialog__headerbtn">
              <i class="el-dialog__close el-icon el-icon-close"></i>
            </button>
          </div>
        </div>
        <el-form :model="formAdd">
          <dynamic-crud :data="tableDataAdd" :option="tableOptionAdd" title="手工清出明细"></dynamic-crud>
          <avue-form
            v-model="formAdd.swStHandworkCleanRecord"
            :option="formOptionAdd"
            style="margin-top:38px"
          ></avue-form>
          <div class="bottom-menu">
            <el-button type="primary" @click="confirmObj">收款人确认</el-button>
            <el-button type="primary" @click="handEdit">保存</el-button>
            <el-button type="primary" @click="editVisableDialog=false">取消</el-button>
          </div>
        </el-form>
      </el-dialog>

      <el-dialog
        :visible.sync="viewVisableDialog"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :fullscreen="viewchangeDialogFlag"
        :destroy-on-close="true"
        width="60%"
      >
        <div slot="title">
          <div>
            <span class="el-dialog__title">预 览</span>
            <div class="avue-crud__dialog__menu">
              <button
                class="el-dialog__headerbtn"
                style="margin-right:20px"
                @click.stop="viewchangeDialog"
              >
                <i class="el-dialog__close el-icon-full-screen"></i>
              </button>
            </div>
            <button type="button" aria-label="Close" class="el-dialog__headerbtn">
              <i class="el-dialog__close el-icon el-icon-close"></i>
            </button>
          </div>
        </div>
        <div class="header">手工清出明细</div>
        <el-form :model="formAdd">
          <avue-crud :data="tableDataAdd" :option="tableOptionView" title="手工清出明细"></avue-crud>
          <avue-form
            v-model="formAdd.swStHandworkCleanRecord"
            :option="formOptionView"
            style="margin-top:38px"
          ></avue-form>
          <div class="bottom-menu">
            <el-button type="primary" @click="viewVisableDialog=false">取消</el-button>
          </div>
        </el-form>
      </el-dialog>
      <open-dialog title="历史记录" :DialogVisible.sync="visableDialogRecords">
        <el-form label-width="60px">
          <avue-crud
            :data="tableDataRecords"
            :option="formOptionViewRecords"
          >
            <template slot="menu" slot-scope="scope">
              <el-button
                icon="el-icon-check"
                :size="scope.size"
                :type="scope.type"
                @click="openRecordsDetail(scope.row,scope.index)"
                >查看明细记录</el-button
              >
            </template>
          </avue-crud>
          <div class="bottom-menu-records">
            <el-button type="primary" @click="visableDialogRecords = false"
              >取消</el-button
            >
          </div>
        </el-form>
      </open-dialog>
      <open-dialog title="历史明细记录" :DialogVisible.sync="visableDialogRecordsDetail">
        <el-form label-width="60px">
          <avue-crud
            :data="tableDataDetailRecords"
            :option="tableOptionViewRecords"
          >
          </avue-crud>
          <div class="bottom-menu-records">
            <el-button @click="visableDialogRecordsDetail = false"
              >关闭</el-button
            >
          </div>
        </el-form>
      </open-dialog>
    </basic-container>
    <addReportEditor ref="addReportEditor" @addReportSuccess="getList"></addReportEditor>
  </div>
</template>



<script>
import {
  fetchList,
  getObj,
  addObj,
  putObj,
  delObj,
  delsObj,
  exportExcel,
  getHandworkCleanRecord,
  queryPastRecords,
  queryPastRecordsDetail,
  getPeriods
} from "@/api/subwaystm/swsthandworkcleanrecord";
import { checkPwd,checkPwdByAccount } from "@/api/admin/user";
import { tableOption } from "@/const/crud/subwaystm/swsthandworkcleanrecord";
import {
  tableOptionAdd,
  formOptionAdd,
  formOptionView,
  tableOptionView,
  formOptionViewRecords,
  tableOptionViewRecords
} from "@/const/crud/subwaystm/swsthandworkcleanrecordAdd";
import { mapGetters } from "vuex";
import baseCrud from '@/mixins/base-crud';
import store from '@/store';
import { dateFormat } from "@/util/date";
import {validatenull} from "@/util/validate";
import transitUtil from "@/api/subwayRat/transitUtil";
import addReportEditor from '@/views/stationTiecketManager/xianWngCJXXQR/BBCCGG/BBCCGGSQ/Editor';

export default {
  name: "swsthandworkcleanrecord",
  mixins: [baseCrud('subwaystm/swsthandworkcleanrecord')],
  components: {
    addReportEditor
  },
  data() {
    return {
      searchForm:{
        approvalStatus:'0'
      },
      visableDialogRecords: false,
      visableDialogRecordsDetail: false,
      tableDataRecords: [],
      tableDataDetailRecords: [],
      recordsId: [],
      formOptionViewRecords: formOptionViewRecords,
      tableOptionViewRecords: tableOptionViewRecords,
      formAdd: {
        swStHandworkCleanRecord: {},
        details: [],
      },
      dialogFormVisible: false,
      saveFlag: false,
      form1: {},
      tableOptionAdd: tableOptionAdd,
      formOptionAdd: formOptionAdd,
      formOptionView: formOptionView,
      tableOptionView: tableOptionView,
      tableDataAdd: [],
      addVisableDialog: false,
      addchangeDialogFlag: false,
      editVisableDialog: false,
      editchangeDialogFlag: false,
      viewVisableDialog: false,
      viewchangeDialogFlag: false,
      settleDateAll:{
        startSettleDate:'',
        endSettleDate:''
      },
      selectKeys:[]
    };
  },
  computed: {
    ...mapGetters(["permissions"]),
    permissionList() {
      return {
        addBtn: this.vaildData(
          this.permissions.swsthandworkcleanrecord_add,
          false
        ),
        delBtn: this.vaildData(
          this.permissions.swsthandworkcleanrecord_del,
          false
        ),
        editBtn: this.vaildData(
          this.permissions.swsthandworkcleanrecord_edit,
          false
        ),
      };
    },
  },
  created() {
    this.otherVueAction();
  },
  watch: {},
  methods: {
    rowAdd(callback){
      // 默认清出金额为0
      callback({
        clearOutAmount: 0,
        clearOutPaperAmount: 0
      })
    },
    async submitData() {
      if (this.$refs.crud.tableSelect.length < 1) {
        this.$message.error("请选择数据");
        return false;
      }
      if (this.$refs.crud.tableSelect.length != 1) {
        this.$message.error("只能选择一条数据");
        return false;
      }
      let params = {};
      let cleanTimes = "";
      let res = false;
      let ress = false;
      for (const table of this.$refs.crud.tableSelect) {
        if (table.approvalStatus != "1") {
          this.$message.error("请选择已提交的数据");
          return false;
        }else{
          let now = new Date(table.cleanTime);
          cleanTimes = dateFormat(now).substring(0, 10);
          params = {
            lineCode: table.lineCode,
            stationCode: table.stationCode,
            revenueTime: cleanTimes
          };
          this.getPeriods(params);
          if (table.isAddReprotError == "1") {
            res = await this.$confirm('该数据已加入报表差错，是否重新加入？', '提示', {
              confirmButtonText: '是',
              cancelButtonText: '否',
              type: 'warning'
            });
            if (!res) {
              return;
            }else{
              ress = true;
            }
          }
        }
      }
      if(res==false){
        ress = await this.$confirm("是否加入报表差错", "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning"
        });
      }
      if (!ress) {
        return;
      }
      this.selectKeys = this.$refs.crud.tableSelect;
      let param={
        dialogTitle: "加入报表差错",
        diffAmountId:this.selectKeys[0].id,
        dataSourceTable:"sw_st_handwork_clean_record",
        lineCode:this.selectKeys[0].lineCode,
        stationCode:this.selectKeys[0].stationCode,
        //tvmCode:this.selectKeys[0].tvmCode,
        reprotTime:this.settleDateAll.endSettleDate,
        reportNameId:6,
        settleBeginTime:this.settleDateAll.startSettleDate,
        settleEndTime:this.settleDateAll.endSettleDate,
        userCodes:this.selectKeys[0].payeePersonJobNo,
	dutyStationLeaderCode: this.selectKeys[0].entryUpdateJobNo, 
	dutyStationLeaderName: this.selectKeys[0].entryUpdateJobName,
        showType:3,
        dataSource:1,
        page:this.page
      };
      this.$refs.addReportEditor.others_report_add_call(param);
    },
    async getPeriods(params){
      await getPeriods(params).then((res)=>{
        if(res!=""){
          let beginTime = res.data.beginTime;
          let endTime = res.data.endTime;
          let now = new Date(beginTime);
          let nows = new Date(endTime);
          this.settleDateAll.startSettleDate = dateFormat(now).substring(0, 10);
          this.settleDateAll.endSettleDate = dateFormat(nows).substring(0, 10);
        }
      });
    },
    async queryPastRecords(row){
      let param={};
      let listRecords = [];
      param.id=row.id;
      var that = this
      await queryPastRecords(param)
        .then(res => {
          listRecords = res.data.data;
          for( var item of listRecords){
            this.tableDataRecords.push(item.logInfo);
            this.recordsId.push(item.id);
          }
        })
    },
    openPastRecords(row){
      this.tableDataRecords = [];
      this.queryPastRecords(row);
      this.visableDialogRecords=true;
    },
    async queryPastRecordsDetail(param){
      await queryPastRecordsDetail(param)
        .then(res => {
          this.tableDataDetailRecords = res.data.data;
        })
    },
    openRecordsDetail(row,index){
      let param={};
      for(var i=0;i<this.recordsId.length;i++){
        if(i==index){
          param.id = this.recordsId[i];
          this.queryPastRecordsDetail(param);
        }
      }
      this.visableDialogRecordsDetail=true;
    },
    myAdd: function () {
      this.form1={};
      for (var i in this.formAdd.swStHandworkCleanRecord) {
        this.formAdd.swStHandworkCleanRecord[i] = null;
      }
      this.formAdd.swStHandworkCleanRecord = {};
      this.tableDataAdd = [];
      this.addVisableDialog = true;
      let now = new Date();
      setTimeout(() => {
        if (now.getHours() < 6) {
          now.setDate((now.getDate() - 1));
          this.formAdd.swStHandworkCleanRecord.cleanTime = dateFormat(now).substr(0, 10) + " 02:00:00";
        }else{
          this.formAdd.swStHandworkCleanRecord.cleanTime = dateFormat(now);
        }
      });
      this.saveFlag = false;
    },
    myView: function (row) {
      getObj(row.id).then((response) => {
        let res = response.data.data;
        this.tableDataAdd = res.details;
        this.formAdd.swStHandworkCleanRecord = res.swStHandworkCleanRecord;
      }).then(()=>{
        this.viewVisableDialog = true;
      });
    },
    myEdit: function (row) {
      this.form1={};
      getObj(row.id).then((response) => {
        let res = response.data.data;
        this.tableDataAdd = res.details;
        for (const item of this.tableDataAdd) {
          item.$cellEdit = true;
        }
        this.formAdd.swStHandworkCleanRecord = res.swStHandworkCleanRecord;
      }).then(()=>{
      this.editVisableDialog = true;
      this.saveFlag = false;
      });
    },
    addchangeDialog: function () {
      if (this.addchangeDialogFlag) {
        this.addchangeDialogFlag = false;
      } else {
        this.addchangeDialogFlag = true;
      }
    },
    editchangeDialog: function () {
      if (this.editchangeDialogFlag) {
        this.editchangeDialogFlag = false;
      } else {
        this.editchangeDialogFlag = true;
      }
    },
    viewchangeDialog: function () {
      if (this.viewchangeDialogFlag) {
        this.viewchangeDialogFlag = false;
      } else {
        this.viewchangeDialogFlag = true;
      }
    },
    save: function () {
      if(this.tableDataAdd.length==0){
        this.$message.info("请添加手工清出明细信息");
        return
      }
      for(const item of this.tableDataAdd){
        if(this.validatenull(item.tvmCode)){
          this.$message.info("请选择TVM编号！")
          return
        }
        if(this.validatenull(item.clearOutAmount) || this.validatenull(item.clearOutPaperAmount)){
          this.$message.info("请填写清出金额(硬币)和清出金额(纸币)");
          return
        }
        if(item.clearOutAmount<=0 && item.clearOutPaperAmount<=0){
          this.$message.info("清出金额(硬币)和清出金额(纸币)至少填入一个有金额的");
          return
        }
      }
      if(this.validatenull(this.formAdd.swStHandworkCleanRecord.payPersonJobNo)||this.validatenull(this.formAdd.swStHandworkCleanRecord.cleanTime)){
        this.$message.info("交款人名称和清出时间为必填项！不能为空");
        return
      }
      if(this.validatenull(this.formAdd.swStHandworkCleanRecord.remark)==false){      
	 if(this.formAdd.swStHandworkCleanRecord.remark.length>500){
	     this.$message.error("字数超过限制，请修改在500字以内！");
             return false;
	 }
      }
      if (!this.saveFlag) {
        this.$message.error("请先点击收款人确认按钮进行确认！");
        return false;
      }
      this.formAdd.details = this.tableDataAdd;
      // let now = new Date();
      // let future = new Date();
      // if (now.getHours() < 6) {
      //   now.setDate(now.getDate() - 1);
      // }else{
      //   future.setDate(now.getDate() + 1);
      // }
      // if(
      //   this.formAdd.swStHandworkCleanRecord.cleanTime >= dateFormat(future).substr(0, 10) + " 02:00:00" || 
      //   this.formAdd.swStHandworkCleanRecord.cleanTime < dateFormat(now).substr(0, 10) + " 02:00:00"
      // ){
      this.$confirm("手工清出时间须按照实际清出日期时间录入系统，录入时间规则为次日2点前数据计算为前一日数据，若超过此时间范围，须点击重新生成车站营收日报", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        addObj(this.formAdd)
          .then((data) => {
            this.$message.success("添加成功");
            this.addVisableDialog = false;
            this.getList(this.page);
            done();
          })
          .catch(() => {
            this.addVisableDialog = false;
          });
      })
      // } else {
      //   addObj(this.formAdd)
      //     .then((data) => {
      //       this.$message.success("添加成功");
      //       this.addVisableDialog = false;
      //       this.getList(this.page);
      //       done();
      //     })
      //     .catch(() => {
      //       this.addVisableDialog = false;
      //     });
      // }
    },
    handEdit: function () {
      if(this.tableDataAdd.length==0){
        this.$message.info("请添加手工清出明细信息");
        return
      }
      for(const item of this.tableDataAdd){
        if(this.validatenull(item.tvmCode)){
          this.$message.info("请选择TVM编号！")
          return
        }
        if(this.validatenull(item.clearOutAmount) || this.validatenull(item.clearOutPaperAmount)){
          this.$message.info("请填写清出金额(硬币)和清出金额(纸币)");
          return
        }
      }
      if(this.validatenull(this.formAdd.swStHandworkCleanRecord.payPersonJobNo)||this.validatenull(this.formAdd.swStHandworkCleanRecord.cleanTime)){
        this.$message.info("交款人名称和清出时间为必填项！不能为空");
        return
      }
      if(this.validatenull(this.formAdd.swStHandworkCleanRecord.remark)==false){
         if(this.formAdd.swStHandworkCleanRecord.remark.length>500){
	     this.$message.error("字数超过限制，请修改在500字以内！");
             return false;
	 }
      }
      if (!this.saveFlag) {
        this.$message.error("请先点击收款人确认按钮进行确认！");
        return false;
      }
      this.formAdd.details = this.tableDataAdd;
      this.$confirm("手工清出时间须按照实际清出日期时间录入系统，录入时间规则为次日2点前数据计算为前一日数据，若超过此时间范围，须点击重新生成车站营收日报", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        putObj(this.formAdd)
          .then((data) => {
            this.$message.success("修改成功");
            this.editVisableDialog = false;
            this.getList(this.page);
            done();
          })
          .catch(() => {
            this.editVisableDialog = false;
          });
        })
    },
    delBatch: function () {
      if (this.$refs.crud.tableSelect.length < 1) {
        this.$message.error("请勾选数据");
        return false;
      }
      let ids = [];
      for (const table of this.$refs.crud.tableSelect) {
        if (table.approvalStatus != "0") {
          this.$message.error("请选择未提交的数据");
          return false;
        }
        ids.push(table.id);
      }
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        delsObj(ids)
          .then((data) => {
            this.$message.success("删除成功");
            this.getList(this.page);
            done();
          })
          .catch(() => {
            loading();
          });
        });  
    },
    getExcel(page, params) {
      this.tableLoading = true;
      exportExcel(
        Object.assign(
          {
            current: page.currentPage,
            size: page.pageSize,
          },
          params,
          this.searchForm
        )
      );
      this.tableLoading = false;
    },
    confirmObj() {
      if (this.validatenull(this.formAdd.swStHandworkCleanRecord.payeePersonJobNo)) {
        this.$message.error("请选择收款人！");
        return;
      }
      this.$prompt("请输入收款人密码", "确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputType: "password",
        inputValidator: (val) => {
          if (!val) return "请输入密码";
        },
      })
        .then(({ value }) => {
          return checkPwd(this.formAdd.swStHandworkCleanRecord.payeePersonJobNo, value);
        })
        .then((response) => {
          var result = response.data.data;
          if (result) {
            this.$message.success("确认成功");
            this.saveFlag = true;
            return;
          } else {
            this.$message.error("密码错误");
            return Promise.reject("密码错误");
          }
        })
        .catch((error) => {
          this.saveFlag = false;
        });
    },
    // confirmObj(){
    //   this.form1={};
    //   this.dialogFormVisible=true;
    // },
    confirmUser: function () {
      if(this.validatenull(this.form1.name) || this.validatenull(this.form1.password)){
        this.$message.warning("请输入账号和密码！");
        return false;
      }
      // if(this.form1.name == store.getters.userInfo.username){
      //   this.$message.warning("不能本人进行确认！");
      //   return false;
      // }
      checkPwdByAccount(this.form1.name, this.form1.password).then((response) => {
        let data = response.data.data;
        if (data) {
          this.$message.success("输入正确");
          this.dialogFormVisible = false;
          this.saveFlag = true;
        } else {
          this.$message.error("用户名或密码不正确！");
        }
        // let code = response.data.code;
        // if (code == "0") {
        //   this.$message.success("输入正确");
        //   this.dialogFormVisible = false;
        //   this.saveFlag = true;
        // } else if (code == "1") {
        //   this.$message.error(response.data.msg);
        // }
      });
    },
    handleUpdate: function (row, index, done, loading) {
      if (!this.saveFlag) {
        this.$message.error("请先点击收款人确认按钮进行确认！");
        return false;
      }
      this.swStHandworkCleanRecordDTO.swStHandworkCleanRecord.cleanTime =
        row.cleanTime;
      this.swStHandworkCleanRecordDTO.swStHandworkCleanRecord.id = row.id;
      this.swStHandworkCleanRecordDTO.swStHandworkCleanRecord.payPersonName =
        row.payPersonName;
      this.swStHandworkCleanRecordDTO.swStHandworkCleanRecord.remark =
        row.remark;
      this.swStHandworkCleanRecordDTO.swStHandworkCleanRecord.payPersonJobNo =
        row.payPersonJobNo;
      this.swStHandworkCleanRecordDTO.details = row.details;
      putObj(this.swStHandworkCleanRecordDTO)
        .then((data) => {
          this.$message.success("修改成功");
          this.getList(this.page);
          this.saveFlag = false;
          done();
        })
        .catch(() => {
          loading();
        });
    },
    otherVueAction(){
      //let th=this;
      transitUtil.$on('updateReport_call_6',(param)=>{
        let p=param;
        getHandworkCleanRecord(p).then(response => {
          this.tableData = response.data.data;
          // this.page.total = response.data.data.total;
          this.tableLoading = false;
        })
      });
    }
  },
};
</script>
<style lang="scss" scoped>
.header {
  margin: 0 auto;
  width: 99%;
  padding: 5px 10px;
  border: 1px solid #e4e4e4;
  border-bottom: none;
  background-color: #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.bottom-menu {
  text-align: center;
}
.bottom-menu-records {
  margin-top: 30px;
  text-align: center;
}
</style>

